package com.zbkj.crmeb.handler.orderproduct;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.utils.monitor.DingMsgEnum;
import com.utils.monitor.DingTalkMsgUtil;
import com.zbkj.crmeb.merchant.api.service.MerProductService;
import com.zbkj.crmeb.plat.by.dto.*;
import com.zbkj.crmeb.plat.by.dto.attributes.SaleAttribute;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.model.StoreProductDescription;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.tools.model.MoneyExchange;
import com.zbkj.crmeb.tools.service.MoneyExchangeService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: wsl
 * @date: 2024/2/22 0022 22:28
 * @ClassName: ByOrderConfirmHandler
 */
@Component("byOrderProductUpdateHandler")
public class ByOrderProductUpdateHandler extends AbstractOrderProductHandler {
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private StoreProductAttrService storeProductAttrService;
    @Autowired
    private StoreProductDescriptionService storeProductDescriptionService;
    @Autowired
    private MerProductService productService;
    @Autowired
    private MoneyExchangeService moneyExchangeService;


    private static final Logger logger = LoggerFactory.getLogger(ByOrderProductUpdateHandler.class);

    @Override
    public boolean doPreCheck(OrderProductContext context) {
        return true;
    }

    @Override
    public Result doHandler(OrderProductContext context) {
        Result result = new Result();
        String productId = context.getProductId();
        // 查询商品信息
        StoreProduct storeProduct = context.getStoreProduct();
        if (null == storeProduct){
            storeProduct = storeProductService.getById(productId);
        }
        // 查询sku信息
        List<StoreProductAttrValue> storeProductAttrValues = context.getStoreProductAttrValues();
        if (CollectionUtils.isEmpty(storeProductAttrValues)){
            storeProductAttrValues = storeProductAttrValueService.getListByProductId(Integer.valueOf(productId));
        }
        List<String> validateList = new ArrayList<>();
        // 组装别样商品参数
        ApiProduct apiProduct = assembledProduct(storeProduct,storeProductAttrValues,validateList);
        if (null == apiProduct){
            return Result.getFailureResult("组装别样商品参数异常",JSON.toJSONString(validateList));
        }
        // 推送别样平台
        MultiValueMap<String,String> header = new LinkedMultiValueMap<>();
        header.put("Authorization",Collections.singletonList("Bearer bxl_test_47ebf2f079c446bab653bac690900f8c"));
        String response = post("https://eurus-dev.bybieyang.com/inventory/api/v1/products", JSON.toJSONString(apiProduct), header);

        DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,"推送商品记录："+response);

        JSONObject jsonObject = JSON.parseObject(response);
        // 失败
        if (null != jsonObject.get("error")){
            ByResult byResult = JSON.parseObject(response, ByResult.class);
            validateList.add(byResult.getError().getMessage());
            result.setData(validateList);
            result.setMessage(byResult.getError().getMessage());
            result.setSuccess(false);
            return result;
        }
        if (CollectionUtils.isNotEmpty(validateList)){
            result.setData(validateList);
        }
        context.setApiProduct(apiProduct);
        result.setSuccess(true);
        return result;
    }

    @Override
    public void doAfter(OrderProductContext context,Result result) {
        List<StoreProductAttrValue> storeProductAttrValues = context.getStoreProductAttrValues();
        Map<String, StoreProductAttrValue> map= storeProductAttrValues.stream().collect(Collectors.toMap(StoreProductAttrValue::getSelfSourceSkuId, v -> v));
        ApiProduct apiProduct = context.getApiProduct();
        for (Sku skus : apiProduct.getSkus()) {
            if (!map.containsKey(skus.getMerchantSkuId())){
                continue;
            }
            StoreProductAttrValue storeProductAttrValue = map.get(skus.getMerchantSkuId());
            storeProductAttrValue.addFeature("pushPlat","Y");

            LambdaUpdateWrapper<StoreProductAttrValue> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(StoreProductAttrValue::getProductId,storeProductAttrValue.getProductId());
            wrapper.eq(StoreProductAttrValue::getSelfSourceSkuId,storeProductAttrValue.getSelfSourceSkuId());
            wrapper.set(StoreProductAttrValue::getFeature,storeProductAttrValue.getFeature());
            storeProductAttrValueService.update(wrapper);
        }

    }

    private ApiProduct assembledProduct(StoreProduct storeProduct, List<StoreProductAttrValue> storeProductAttrValues, List<String> validateList) {
        ApiProduct apiProduct = new ApiProduct();
        apiProduct.setMerchantProductId(storeProduct.getBarCode().replace(" ",""));
        apiProduct.setId("avitahk_"+storeProduct.getKeyword());
        // todo
        apiProduct.setCategoryId("751");
        // todo
        apiProduct.setBrandId("41fd220f-05ed-3d8c-96e3-b83af87d45d7");
        apiProduct.setName(storeProduct.getStoreName()+" "+storeProduct.getKeyword());
        apiProduct.setStatus("AVAILABLE");

        String productErrorKey = String.format("商品名:%s--->商品id:%s--->异常信息: ",storeProduct.getStoreName(),storeProduct.getId());
        StoreProductDescription storeProductDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery().eq(StoreProductDescription::getProductId, storeProduct.getId()));
        if (StringUtils.isBlank(storeProductDescription.getSliderImage())){
            validateList.add(productErrorKey+"商品缺失主图或轮播图");
            return null;
        }
        // todo 主图
//        String mainImageUrl = storeProductDescription.getImage();
        List<ProductImageDTO> mainProductImageDTOS = new ArrayList<>();
        String sliderImage = storeProductDescription.getSliderImage();
        List<String> split = JSON.parseArray(sliderImage, String.class);
        int mainImageIndex = 0;
        for (String imageUrl : split) {
            if (mainImageIndex>4){
                break;
            }
            ImageUploadResponse imageUploadResponse = FileUploadUtils.uploadImageOfBY(imageUrl);
            if (null == imageUploadResponse){
                continue;
            }
            ProductImageDTO mainImage = new ProductImageDTO();
            mainImage.setId(imageUploadResponse.getId());
            mainImage.setIndex(mainImageIndex);
            mainProductImageDTOS.add(mainImage);
            mainImageIndex++;
        }
        apiProduct.setImages(mainProductImageDTOS);

        // 商品详情数据
        ImageTextDTO imageTextDTO = new ImageTextDTO();
        List<LayerDTO> layerDTOS = new ArrayList<>();
        if (StringUtils.isNotBlank(storeProductDescription.getDescription())){
            LayerDTO layerDTO = new LayerDTO();
            TextDTO textDTO = new TextDTO();
            textDTO.setText(storeProductDescription.getDescription());
            layerDTO.setLayerType("TEXT");
            layerDTO.setText(textDTO);
            layerDTOS.add(layerDTO);
        }
        String sp1 = storeProductDescription.getSp1();
        if (StringUtils.isNotBlank(sp1)){
            List<String> iamgesArray = JSON.parseArray(sp1, String.class);
            int descIndex = 0;
            for (String image : iamgesArray) {
                LayerDTO layerDTO = new LayerDTO();
                ImageUploadResponse imageUploadResponse = FileUploadUtils.uploadImageOfBY(image);
                if (null == imageUploadResponse){
                    continue;
                }
                ImageDTO imageDTO = new ImageDTO();
                imageDTO.setUrl(imageUploadResponse.getUrl());
                imageDTO.setFormat(imageUploadResponse.getFormat());
                imageDTO.setWidth(imageUploadResponse.getWidth());
                imageDTO.setHeight(imageUploadResponse.getHeight());
                layerDTO.setImage(imageDTO);
                layerDTO.setLayerType("IMAGE");
                layerDTOS.add(layerDTO);
            }
        }
        if (CollectionUtils.isNotEmpty(layerDTOS)){
            imageTextDTO.setLayers(layerDTOS);
            apiProduct.setDescription(imageTextDTO);
        }
        // 计算金额
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("merId",126);
        THREAD_LOCAL.set(jsonObject);
//        MybatisPlusConfig.tableNameMp.set(TableNameUtil.getProductMerName(126));
//        MybatisPlusConfig.productValueNameMp.set(TableNameUtil.getProductMerName(126));
//        ProductDetailResponse productDetailResponse = productService.getDetail(storeProduct.getId(), 126, null);
//        if (null == productDetailResponse || CollectionUtils.isEmpty(productDetailResponse.getProductValues())){
//            validateList.add(productErrorKey+"商品金额计算异常");
//            return null;
//        }
//        List<StoreProductAttrValueResponse> productValues = productDetailResponse.getProductValues();
//        Map<String, StoreProductAttrValueResponse> skuInfoMap = productValues.stream().collect(Collectors.toMap(StoreProductAttrValueResponse::getSourceSkuId, v -> v));
        MoneyExchange moneyExchange = moneyExchangeService.getById(12);
        BigDecimal baseExchange = new BigDecimal("7.2");
        if (null != moneyExchange && StringUtils.isNotBlank(moneyExchange.getBankConversionPri())){
            baseExchange = new BigDecimal(moneyExchange.getBankConversionPri());
        }
        // sku数据
        List<Sku> skus = new ArrayList<>();
        for (StoreProductAttrValue storeProductAttrValue : storeProductAttrValues) {
            String skuErrorKey = String.format("商品名:%s--->sku信息:%s--->异常信息: ",storeProduct.getStoreName(),storeProductAttrValue.getSuk());
//            if (!skuInfoMap.containsKey(storeProductAttrValue.getSourceSkuId())){
//                validateList.add(skuErrorKey+"金额异常");
//                continue;
//            }
//            StoreProductAttrValueResponse storeProductAttrValueResponse = skuInfoMap.get(storeProductAttrValue.getSourceSkuId());
            // sku
            Sku sku = new Sku();
            sku.setBarCode(storeProductAttrValue.getSelfSourceSkuId().replace(" ",""));
            sku.setId(UUID.randomUUID().toString().replace("-",""));
            sku.setProductId(apiProduct.getId());
            if (StringUtils.isBlank(storeProductAttrValue.getSelfSourceSkuId())){
                validateList.add(skuErrorKey+"自定义skuId为空");
                continue;
            }
            sku.setMerchantSkuId(storeProductAttrValue.getSelfSourceSkuId().replace(" ",""));
            // todo
            String image = storeProductAttrValue.getImage();
            ImageUploadResponse imageUploadResponse = FileUploadUtils.uploadImageOfBY(image);
            if (null == imageUploadResponse){
                validateList.add(skuErrorKey+"sku图片上传失败");
                continue;
            }
            ProductImageDTO skuImage = new ProductImageDTO();
            skuImage.setId(imageUploadResponse.getId());
            skuImage.setIndex(0);
            sku.setImages(Collections.singletonList(skuImage));
            //todo {"颜色":"默认","尺寸":"黑色;85;"}
            if (StringUtils.isBlank(storeProductAttrValue.getAttrValue())){
                validateList.add(skuErrorKey+"sku缺少产品属性");
                continue;
            }
            JSONObject skuAttribute = JSON.parseObject(storeProductAttrValue.getAttrValue());
            SaleAttribute saleAttribute = new SaleAttribute();
            saleAttribute.setKey("SIZE");
            saleAttribute.setName(skuAttribute.getString("尺寸"));
            sku.setSaleAttributes(Collections.singletonList(saleAttribute));
            // todo
//            Price originalPrice = new Price();
//            originalPrice.setCurrency("USD");
//            originalPrice.setValue(storeProductAttrValue.getPrice().multiply(BigDecimal.valueOf(100L)).intValue());
//            sku.setOriginalPrice(originalPrice);

            Price salePrice = new Price();
            salePrice.setCurrency("USD");
//            salePrice.setValue(storeProductAttrValueResponse.getPrice()
//                    .divide(baseExchange,2, RoundingMode.DOWN).multiply(BigDecimal.valueOf(100L)).setScale(2, RoundingMode.DOWN).intValue());
            salePrice.setValue(storeProductAttrValue.getPrice()
                    .divide(baseExchange,2, RoundingMode.DOWN).multiply(BigDecimal.valueOf(100L)).setScale(2, RoundingMode.DOWN).intValue());
//            sku.setSalePrice(salePrice);
            sku.setSupplyPrice(salePrice);
            sku.setStockNum(storeProductAttrValue.getStock());
            sku.setStatus("AVAILABLE");
            skus.add(sku);
        }
        apiProduct.setSkus(skus);
        return apiProduct;

    }

    public static String post(String url, String params, MultiValueMap<String, String> headers) {
        return request(url, params, headers, HttpMethod.POST, MediaType.APPLICATION_JSON);
    }

    /**
     * http请求
     *
     * @param url
     * @param params    请求参数
     * @param headers   请求头
     * @param method    请求方式
     * @param mediaType 参数类型
     * @return
     */
    public static String request(String url, Object params, MultiValueMap<String, String> headers, HttpMethod method, MediaType mediaType) {
        if (url == null || url.trim().isEmpty()) {
            return null;
        }
        RestTemplate client = new RestTemplate();
        // header
        HttpHeaders httpHeaders = new HttpHeaders();
        if (headers != null) {
            httpHeaders.addAll(headers);
        }
        // 提交方式：表单、json
        httpHeaders.setContentType(mediaType);
        HttpEntity<Object> httpEntity = new HttpEntity(params, httpHeaders);
        ResponseEntity<String> response = client.exchange(url, method, httpEntity, String.class);
        return response.getBody();
    }




}
